// models/category.js
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");

const Category = sequelize.define(
  "Category",
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: "分类唯一标识符",
    },
    name: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: "分类名称",
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: "分类描述",
    },
    parentId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: "父分类ID，用于实现多级分类",
    },
    image: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "分类图片URL",
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: "分类排序顺序",
    },
    status: {
      type: DataTypes.ENUM("active", "inactive"),
      defaultValue: "active",
      comment: "分类状态",
    },
  },
  {
    tableName: "categories",
    timestamps: true,
    comment: "商品分类表",
    indexes: [
      {
        name: "K_parentId",
        fields: ["parentId"],
      },
      {
        name: "K_sortOrder",
        fields: ["sortOrder"],
      },
    ],
  }
);

// 分类关联定义
Category.associate = function (models) {
  // 一个分类可以有多个子分类
  Category.hasMany(models.Category, {
    foreignKey: "parentId",
    as: "children",
  });

  // 一个分类属于一个父分类
  Category.belongsTo(models.Category, {
    foreignKey: "parentId",
    as: "parent",
  });

  // 一个分类可以有多个商品
  Category.hasMany(models.Product, {
    foreignKey: "categoryId",
    as: "products",
  });
};

module.exports = Category;
